#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int tickets = 1000;
void *start_routine(void *args)
{
    string name = static_cast<const char *>(args);
    while (1)
    {
        pthread_mutex_lock(&mutex);

        pthread_cond_wait(&cond, &mutex);
        cout << name << " -->" << tickets << endl;
        tickets--;

        pthread_mutex_unlock(&mutex);
    }
}
int main()
{
// pthread_t t1, t2;
// pthread_create(&t1, nullptr, start_routine, (void *)"thread one");
// pthread_create(&t2, nullptr, start_routine, (void *)"thread two");

// 5个线程
#define NUM 5
    pthread_t t[NUM];
    for (int i = 0; i < NUM; i++)
    {
        char *buffer = new char[64];
        snprintf(buffer, 64, "thread %d", i + 1);
        pthread_create(t + i, nullptr, start_routine, (void *)buffer);
    }
    while (1)
    {
        sleep(1);
        //pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
        cout << "main thread wakeup one thread ..." << endl;
    }

    // pthread_join(t1, nullptr);
    // pthread_join(t2, nullptr);

    for (int i = 0; i < NUM; i++)
    {
        pthread_join(t[i], nullptr);
    }
    return 0;
}